package com.cccyy.pdf;

import cn.hutool.core.convert.Convert;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.parser.PdfCanvasProcessor;
import com.itextpdf.kernel.pdf.canvas.parser.listener.IPdfTextLocation;
import com.itextpdf.kernel.pdf.canvas.parser.listener.RegexBasedLocationExtractionStrategy;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public class PdfUtil {
    private static Logger logger = LoggerFactory.getLogger(PdfUtil.class);
    private static final float IMG_WIDTH = 100;
    private static final float IMG_HEIGHT = 35;
    private static final float x_offset = -100;
    private static final float y_offset = 0;

    private static final List<String> keyWords = Arrays.asList("本页内容结束");


    public static void main(String[] args) throws Exception {
//        Path path = Paths.get("resources/testPdfSign/c73e88045a09af39923a83d74df4d5a4.png");
//        System.out.println("绝对路径: " + path.toAbsolutePath()); // 打印实际路径
//
//        String basePath = System.getProperty("user.dir"); // 当前工作目录
//        System.out.println("当前工作目录: " + basePath); // 打印实际路径
//        Path filePath = Paths.get(basePath, "resources/testPdfSign/c73e88045a09af39923a83d74df4d5a4.png");
//        System.out.println("绝对路径: " + filePath.toAbsolutePath()); // 打印实际路径


        //通过指定pdf文件名，指定关键字，和指定的pdf文件的待处理页数做参数
        boolean result = getKeyWordsAndInsertImg("src/main/resources/testPdfSign/051713543md4.pdf", "src/main/resources/testPdfSign/c73e88045a09af39923a83d74df4d5a4.png", keyWords);

    }


//    315066591673638912(businessId)  315066732715462656(fileId)
//    userSign1756112521551,userSign1758528745155,userSign1758528752264,userSign1759042373211 (关键字)

    /**
     * 得到关键字位置插入图片
     *
     * @param sourcePath  源文件
     * @param imagePath   图片位置
     * @param keyWordList 关键字列表
     */
    public static boolean getKeyWordsAndInsertImg(String sourcePath, String imagePath, List<String> keyWordList) {
        try {
            //得到需要插入的图片
            ImageData imageData = ImageDataFactory.create(imagePath);
            //核心思路为对PdfDocument对象采用某种Strategy，这里使用RegexBasedLocationExtractionStrategy
            PdfReader pr = new PdfReader(sourcePath);

            //临时路径
//            String UUID = UUIDUtils.createUUID();
            long l = System.currentTimeMillis();
            String str = Convert.toStr(l);
            String tempPath = sourcePath.replace(".pdf", "_" + str + ".pdf");
            //生成新的PDF文件
            PdfDocument pd = new PdfDocument(pr, new PdfWriter(tempPath));
            Document document = new Document(pd);
            int pageCount = pd.getNumberOfPages();
            boolean insertFlag = false;
            for (String s : keyWordList) {
                //遍历每一页
                for (int i = 1; i <= pageCount; i++) {
                    PdfPage page = pd.getPage(i);
                    //查找页中的匹配文字，并定位到位置。
                    RegexBasedLocationExtractionStrategy strategy = new RegexBasedLocationExtractionStrategy(s);
                    PdfCanvasProcessor processor = new PdfCanvasProcessor(strategy);
                    processor.processPageContent(page);
                    Collection<IPdfTextLocation> resultantLocations = strategy.getResultantLocations();

                    //自定义结果处理
                    if (!resultantLocations.isEmpty()) {
                        for (IPdfTextLocation item : resultantLocations) {
                            Rectangle boundRectangle = item.getRectangle();
                            System.out.println(item.getText());
                            System.out.println("关键字“" + s + "” 的坐标为 x: " + boundRectangle.getX() + "  ,y: " + boundRectangle.getY());
                            Image image = new Image(imageData).scaleAbsolute(IMG_WIDTH, IMG_HEIGHT).setFixedPosition(i, boundRectangle.getRight() + x_offset, boundRectangle.getBottom() + y_offset);
                            document.add(image);
                            insertFlag = true;
                            break;
                        }
                        break;
                    }
                }
            }

            document.close();
            pr.close();
            pd.close();
            if (insertFlag) {
                logger.info("图片插入成功！");
            } else {
                logger.error("图片插入失败！");
                return false;
            }

//            File oldfile = new File(sourcePath);
//            oldfile.delete();
//            boolean is = new File(tempPath).renameTo(new File(sourcePath));
//            if (is) {
//                logger.info("文件重命名成功！");
//            } else {
//                logger.error("文件重命名失败！");
//                return false;
//            }


        } catch (Exception e) {
            e.printStackTrace();
            logger.error("读取文件插入图片失败！" + e.getMessage());
            return false;
        }

        return true;
    }


//    public static void getKeyWordsAndInsertImg(InputStream fileStream, InputStream imgStream, List<String> keywords) {
//        try {
//            //得到需要插入的图片
//            byte[] imgBytes = readStream(imgStream);
//            ImageData imageData = ImageDataFactory.create(imgBytes);
//            imgStream.close();
//            //核心思路为对PdfDocument对象采用某种Strategy，这里使用RegexBasedLocationExtractionStrategy
//            PdfReader pr = new PdfReader(fileStream);
//
//            //生成新的PDF文件
//            PdfDocument pd = new PdfDocument(pr);
//            Document document = new Document(pd);
//            int pageCount = pd.getNumberOfPages();
//
//            for (String keyword : keywords) {
//                //遍历每一页
//                for (int i = 1; i <= pageCount; i++) {
//                    PdfPage page = pd.getPage(i);
//                    //查找页中的匹配文字，并定位到位置。
//                    RegexBasedLocationExtractionStrategy strategy = new RegexBasedLocationExtractionStrategy(keyword);
//                    PdfCanvasProcessor processor = new PdfCanvasProcessor(strategy);
//                    processor.processPageContent(page);
//                    Collection<IPdfTextLocation> resultantLocations = strategy.getResultantLocations();
//
//                    //自定义结果处理
//                    if (!resultantLocations.isEmpty()) {
//                        for (IPdfTextLocation item : resultantLocations) {
//                            Rectangle boundRectangle = item.getRectangle();
//                            System.out.println(item.getText());
//                            System.out.println("关键字“" + keyword + "” 的坐标为 x: " + boundRectangle.getX() + "  ,y: " + boundRectangle.getY());
//                            Image image = new Image(imageData).scaleAbsolute(IMG_WIDTH, IMG_HEIGHT).setFixedPosition(i, boundRectangle.getRight() + x_offset, boundRectangle.getBottom() + y_offset);
//                            document.add(image);
//                            logger.info("图片插入成功！关键字-{}", keyword);
//                            break;
//                        }
//                    }
//                    break;
//                }
//            }
//
//            fileStream.close();
//            // 将Document写入到File中
//            pr.close();
//            pd.close();
//            document.close();
//
////            new File(tempPath);
//        } catch (Exception e) {
//            e.printStackTrace();
////            Exceptions.ifTrue(true).throwException("异常");
//        }
//
//    }
//
//    public static byte[] readStream(InputStream input) {
//        ByteArrayOutputStream output = new ByteArrayOutputStream();
//        byte[] buffer = new byte[1024];
//        int len = 0;
//
//        try {
//            while ((len = input.read(buffer)) != -1) {
//                output.write(buffer, 0, len);
//            }
//
//            return output.toByteArray();
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//    }

}

